package com.lc.cehui.ui.activity.land;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.http.listener.OnHttpListener;
import com.hjq.toast.ToastUtils;
import com.lc.cehui.R;
import com.lc.cehui.app.AppActivity;
import com.lc.cehui.base.BaseDialog;
import com.lc.cehui.dialog.AddressDialog;
import com.lc.cehui.dialog.MenuDialog;
import com.lc.cehui.dialog.SelectDialog;
import com.lc.cehui.http.request.CompanyServiceApi;
import com.lc.cehui.http.request.EnterpriseRegisterApi;
import com.lc.cehui.http.request.GetCodeApi;
import com.lc.cehui.http.request.UpdateImageApi;
import com.lc.cehui.http.response.CodeBean;
import com.lc.cehui.http.response.CompanyTypeBean;
import com.lc.cehui.http.response.EnterRegisterBean;
import com.lc.cehui.http.response.RegisterEnterpriseBean;
import com.lc.cehui.http.response.UpdateImageBean;
import com.lc.cehui.manager.InputTextManager;
import com.lc.cehui.ui.activity.mine.AgreeActivity;
import com.lc.cehui.ui.adapter.ImageNineAdapter;
import com.lc.cehui.util.CourseUtils;
import com.lc.cehui.util.constant.EvenConstant;
import com.lc.cehui.util.eventbus.Event;
import com.lc.cehui.util.eventbus.EventBusUtils;
import com.lc.cehui.widget.CountdownView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;


public class RegisterEnterpriseActivity extends AppActivity {

    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_people)
    EditText etPeople;
    @BindView(R.id.et_vx)
    EditText etVx;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.et_address)
    EditText etAddress;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.et_password_agine)
    EditText etPasswordAgine;

    @BindView(R.id.bt_submit)
    Button btSubmit;
    @BindView(R.id.rv_yingyezhizhao)
    RecyclerView rvYingyezhizhao;
    @BindView(R.id.rv_qitazizhi)
    RecyclerView rvQitazizhi;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.cdv_yzm)
    CountdownView cdvYzm;
    @BindView(R.id.service)
    TextView service;
    @BindView(R.id.et_profile)
    EditText etProfile;
    @BindView(R.id.tv_industry)
    TextView tvIndustry;
    @BindView(R.id.nature)
    TextView nature;
    @BindView(R.id.scale)
    TextView scale;
    @BindView(R.id.welfare)
    TextView welfare;
    @BindView(R.id.tv_xieyi)
    TextView tvXieyi;
    @BindView(R.id.tv_yinsi)
    TextView tvYinsi;
    /**
     * 省
     */
    private String mProvince = "";
    /**
     * 市
     */
    private String mCity = "";
    /**
     * 区
     */
    private String mArea = "";
    private RxPermissions rxPermissions;
    private ImageNineAdapter zhizhaoadapter;
    private ImageNineAdapter qitaadapter;
    private String type;
    private String business_picurl;
    private String others_picurl;
    private List<RegisterEnterpriseBean.DataBean> serviceList = new ArrayList<>();
    private List<CompanyTypeBean.DataBean.List2Bean> industryList = new ArrayList<>();
    private List<CompanyTypeBean.DataBean.List2Bean> natureList = new ArrayList<>();
    private List<CompanyTypeBean.DataBean.List2Bean> welfareList = new ArrayList<>();
    private List<CompanyTypeBean.DataBean.List2Bean> scaleList = new ArrayList<>();

    private List<String> dataList = new ArrayList<>();
    private String workid;
    private String industry;
    private String scaleid;
    private String welfareId;
    private String natureId;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_register_enterprise;
    }

    @Override
    protected void initView() {
        InputTextManager.with(this)
                .addView(etName)
                .addView(etPeople)
                .addView(etPhone)
                .addView(etCode)
                .addView(etAddress)
                .addView(etPassword)
                .addView(etPasswordAgine)
                .addView(etVx)
                .setMain(btSubmit)
                .build();
        initAdapter();
    }

    @Override
    protected void initData() {

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        rxPermissions = new RxPermissions(this);
        company_service();
        company_type();
    }
    private void company_type() {

        EasyHttp.post(this)
                .api("api/company_type")
                .request(new HttpCallback<CompanyTypeBean>(this) {

                    @Override
                    public void onSucceed(CompanyTypeBean data) {
                        for (int i = 0; i <data.getData().size() ; i++) {
                            if (data.getData().get(i).getTitle().equals("行业")){
                               industryList.addAll(data.getData().get(i).getList2());
                            }else if (data.getData().get(i).getTitle().equals("性质")){
                                natureList.addAll(data.getData().get(i).getList2());
                            }else if (data.getData().get(i).getTitle().equals("福利")){
                                welfareList.addAll(data.getData().get(i).getList2());
                            }else if (data.getData().get(i).getTitle().equals("规模")){
                                scaleList.addAll(data.getData().get(i).getList2());
                            }
                        }


                    }
                });
    }
    private void company_service() {

        EasyHttp.post(this)
                .api(new CompanyServiceApi())
                .request(new HttpCallback<RegisterEnterpriseBean>(this) {
                    @Override
                    public void onSucceed(RegisterEnterpriseBean data) {

                        serviceList.addAll(data.getData());

                    }
                });
    }

    private void initAdapter() {
        rvYingyezhizhao.setLayoutManager(new GridLayoutManager(this, 3));
        zhizhaoadapter = new ImageNineAdapter(this, new ArrayList<Object>(), true);
        rvYingyezhizhao.setAdapter(zhizhaoadapter);
        rvYingyezhizhao.setNestedScrollingEnabled(false);
        zhizhaoadapter.setOnPhotoClickListener(new ImageNineAdapter.onPhotoClickListener() {
            @Override
            public void onClick(View view, int position) {
                startImageBrowse(zhizhaoadapter.getList(), position);
            }
        });
        zhizhaoadapter.setonDeleteClickListener(new ImageNineAdapter.onDeleteClickListener() {
            @Override
            public void onClick(View view, int position) {
                zhizhaoadapter.getList().remove(position);
                //添加脚布局
                if (zhizhaoadapter.getmFooterView() == null)
                    setFooterView(rvYingyezhizhao, zhizhaoadapter);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        zhizhaoadapter.notifyDataSetChanged();
                    }
                });
            }
        });

        setFooterView(rvYingyezhizhao, zhizhaoadapter);
        rvQitazizhi.setLayoutManager(new GridLayoutManager(this, 3));
        qitaadapter = new ImageNineAdapter(this, new ArrayList<Object>(), true);
        rvQitazizhi.setAdapter(qitaadapter);
        rvQitazizhi.setNestedScrollingEnabled(false);
        qitaadapter.setOnPhotoClickListener(new ImageNineAdapter.onPhotoClickListener() {
            @Override
            public void onClick(View view, int position) {
                startImageBrowse(qitaadapter.getList(), position);
            }
        });
        qitaadapter.setonDeleteClickListener(new ImageNineAdapter.onDeleteClickListener() {
            @Override
            public void onClick(View view, int position) {
                qitaadapter.getList().remove(position);
                //添加脚布局
                if (qitaadapter.getmFooterView() == null)
                    setFooterView(rvQitazizhi, qitaadapter);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        qitaadapter.notifyDataSetChanged();
                    }
                });
            }
        });

        setFooterView(rvQitazizhi, qitaadapter);
    }

    private void setFooterView(RecyclerView view, ImageNineAdapter adapter) {
        View footer = LayoutInflater.from(this).inflate(R.layout.adapter_image_footer, view, false);
        ImageView add = footer.findViewById(R.id.iv_add);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rxPermissions
                        .request(Manifest.permission.CAMERA)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                if (aBoolean) {
                                    if (adapter == qitaadapter) {
                                        type = "qita";
                                        showAlbumlot(PictureConfig.CHOOSE_REQUEST, 5);
                                    } else {
                                        type = "zizhi";
                                        showAlbumlot(PictureConfig.CHOOSE_REQUEST, 1);
                                    }
                                } else {
                                    ToastUtils.show("请求权限失败,相机不可用");
                                }
                            }
                        });
            }
        });
        adapter.setmFooterView(footer);
    }

    @OnClick({R.id.tv_address, R.id.bt_submit, R.id.cdv_yzm, R.id.tv_xieyi, R.id.tv_yinsi,R.id.service, R.id.et_profile, R.id.tv_industry, R.id.nature, R.id.scale, R.id.welfare})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_address:
                new AddressDialog.Builder(this)
                        .setTitle("选择地区")
                        // 设置默认省份
//                        .setProvince(mProvince)
                        // 设置默认城市（必须要先设置默认省份）
//                        .setCity(mCity)
                        // 不选择县级区域
                        //.setIgnoreArea()
                        .setListener((dialog, province, city, area) -> {
                            String address = province + city + area;
                            if (!tvAddress.getText().toString().equals(address)) {
                                mProvince = province;
                                mCity = city;
                                mArea = area;
                                tvAddress.setText(address);
                            }
                        })
                        .show();
                break;

            case R.id.bt_submit:
                company_reg();
                break;
            case R.id.tv_xieyi:
                startActivity(new Intent(RegisterEnterpriseActivity.this, AgreeActivity.class).putExtra("id", "15").putExtra("title", "用户协议"));
                break;
            case R.id.tv_yinsi:
                startActivity(new Intent(RegisterEnterpriseActivity.this, AgreeActivity.class).putExtra("id", "14").putExtra("title", "隐私政策"));
                break;
            case R.id.cdv_yzm:
                if (CourseUtils.isNullOrEmpty(etPhone.getText().toString().trim())) {
                    toast("请输入手机号");
                    return;
                }
                EasyHttp.post(this)
                        .api(new GetCodeApi()
                                .setMobile(etPhone.getText().toString()))
                        .request(new HttpCallback<CodeBean>(this) {

                            @Override
                            public void onSucceed(CodeBean data) {
                                toast(data.getMsg());
                                if (data.getCode().equals("200")) {
                                    cdvYzm.start();
                                }
                            }
                        });
                break;
            case R.id.service:
                dataList.clear();
                for (int i = 0; i < serviceList.size(); i++) {

                    dataList.add(serviceList.get(i).getTitle());
                }
                showMenuDialog(dataList,service);
                break;
            case R.id.et_profile:

                break;
            case R.id.tv_industry:
                dataList.clear();
                for (int i = 0; i < industryList.size(); i++) {

                    dataList.add(industryList.get(i).getTitle());
                }
                showMenuDialog(dataList,tvIndustry);
                break;
            case R.id.nature:
                dataList.clear();
                for (int i = 0; i < natureList.size(); i++) {

                    dataList.add(natureList.get(i).getTitle());
                }
                showMenuDialog(dataList,nature);
                break;
            case R.id.scale:
                dataList.clear();
                for (int i = 0; i < scaleList.size(); i++) {

                    dataList.add(scaleList.get(i).getTitle());
                }
                showMenuDialog(dataList,scale);
                break;
            case R.id.welfare:
                List<String> list = new ArrayList<>();
                for (int i = 0; i < welfareList.size(); i++) {
                    list.add(welfareList.get(i).getTitle());
                }
                new SelectDialog.Builder(this)
                        .setTitle("请选择员工福利")
                        .setList(welfareList)


                        // 设置最大选择数

                        // 设置默认选中

                        .setListener(new SelectDialog.OnListener<CompanyTypeBean.DataBean.List2Bean>() {

                            @RequiresApi(api = Build.VERSION_CODES.N)
                            @Override
                            public void onSelected(BaseDialog dialog, HashMap<Integer, CompanyTypeBean.DataBean.List2Bean> data) {

                                List<CompanyTypeBean.DataBean.List2Bean> welfares = data.values().stream().collect(Collectors.toList());
                                List <Object> welfareIdList=new ArrayList<>();
                                List <Object> welfareTextList=new ArrayList<>();
                                for (int i = 0; i <welfares.size() ; i++) {
                                    welfareIdList.add(welfares.get(i).getId());
                                    welfareTextList.add(welfares.get(i).getTitle());
                                }
                                welfareId=CourseUtils.listToString1(welfareIdList);
                                welfare.setText(CourseUtils.listToString1(welfareTextList));




                            }

                            @Override
                            public void onCancel(BaseDialog dialog) {
                            dialog.dismiss();
                            }
                        })
                        .show();
                break;
        }
    }

    private void showMenuDialog(List<String> dataList,TextView tv_text) {
        new MenuDialog.Builder(this)
                // 设置 null 表示不显示取消按钮
                //.setCancel(getString(R.string.common_cancel))
                // 设置点击按钮后不关闭对话框
                //.setAutoDismiss(false)
                .setList(dataList)
                .setListener(new MenuDialog.OnListener<String>() {

                    @Override
                    public void onSelected(BaseDialog dialog, int position, String string) {
                        tv_text.setText(string);
                        switch (tv_text.getId()){
                            case R.id.service:
                                workid = serviceList.get(position).getId()+"";
                                break;
                            case R.id.tv_industry:
                                industry = industryList.get(position).getId()+"";
                                break;
                            case R.id.scale:
                                scaleid = scaleList.get(position).getId()+"";
                                break;

                            case R.id.nature:
                                natureId = natureList.get(position).getId()+"";
                                break;

                        }

                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {
                      dialog.dismiss();
                    }
                })
                .show();
    }

    private void company_reg() {
        if (!etPassword.getText().toString().trim().equals(etPasswordAgine.getText().toString().trim())) {
            toast("两次输入密码不一致");
        }
        // 提交注册
        EasyHttp.post(this)
                .api(new EnterpriseRegisterApi()
                        .setCnname_wx(etVx.getText().toString())
                        .setNickname(etName.getText().toString())
                        .setMobile(etPhone.getText().toString())
                        .setYzm(etCode.getText().toString())
                        .setPassword(etPassword.getText().toString())
                        .setRepassword(etPasswordAgine.getText().toString())
                        .setCnname(etPeople.getText().toString())
                        .setProvince(mProvince)
                        .setCity(mCity)
                        .setDistrict(mArea)
                        .setCompany_address(etAddress.getText().toString())
                        .setCompany_des(etProfile.getText().toString()).setBusiness_picurl(business_picurl).setOthers_picurl(others_picurl).setIndustry(industry).setNature(natureId).setScale(scaleid).setWelfare(welfareId).setWorkid(workid))
                .request(new HttpCallback<EnterRegisterBean>(this) {


                    @Override
                    public void onSucceed(EnterRegisterBean data) {
                        toast(data.getMsg());
                        if (data.getCode().equals("200")) {
                            EventBusUtils.sendEvent(new Event(EvenConstant.REGISTERFINSH));
                            finish();

                        }
                    }


                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> result = PictureSelector.obtainMultipleResult(data);

                    if (type.equals("zizhi")) {
                        zhizhaoadapter.getList().clear();
                        for (int i = 0; i < result.size(); i++) {

                            getCommon_uploads(new File(result.get(i).getRealPath()));
                        }


                    } else {
                        qitaadapter.getList().clear();
                        for (int i = 0; i < result.size(); i++) {

                            getCommon_uploads(new File(result.get(i).getRealPath()));
                        }

                    }

                    break;
            }
        }
    }

    private void getCommon_uploads(File list) {
        EasyHttp.post(this)
                .api(new UpdateImageApi()
                        .setImg(list))
                .request(new OnHttpListener<UpdateImageBean>() {

                    @Override
                    public void onSucceed(UpdateImageBean data) {
//
                        if (data.getCode().equals("200")) {
                            switch (type) {
                                case "zizhi":
                                    zhizhaoadapter.getList().add(new File(data.getData().getImg()));
                                    business_picurl = CourseUtils.listToString1(zhizhaoadapter.getList());
                                    if (zhizhaoadapter.getList().size() >= 1) {
                                        zhizhaoadapter.removeFooterView();//移除脚布局
                                    }
                                    break;
                                case "qita":
                                    qitaadapter.getList().add(new File(data.getData().getImg()));
                                    others_picurl = CourseUtils.listToString1(qitaadapter.getList());

                                    if (qitaadapter.getList().size() >= 5) {
                                        qitaadapter.removeFooterView();//移除脚布局
                                    }
                                    break;

                            }

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (type.equals("zizhi")) {
                                        Log.e("TAG", "run: " + zhizhaoadapter.getList().size());
                                        zhizhaoadapter.notifyDataSetChanged();
                                    } else {
                                        qitaadapter.notifyDataSetChanged();
                                    }
                                }
                            });
                        }

                    }

                    @Override
                    public void onFail(Exception e) {

                    }
                });
    }



}
